<template>
  <div class="chat-page-container">
    <h2 class="page-title">匿名情绪陪聊</h2>
    <div class="chat-container">
      <!-- 顶部标题栏 -->
      <header class="chat-header">
        <h1>想说就说</h1>
        <button class="privacy-btn" @click="showPrivacy = true">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="16" x2="12" y2="12"></line>
            <line x1="12" y1="8" x2="12.01" y2="8"></line>
          </svg>
          隐私说明
        </button>
      </header>

      <!-- 隐私说明弹窗 -->
      <div v-if="showPrivacy" class="privacy-modal" @click.self="showPrivacy = false">
        <div class="privacy-content">
          <h3>隐私保护说明</h3>
          <p>聊天内容仅你可见，无数据留存</p>
          <button class="close-btn" @click="showPrivacy = false">关闭</button>
        </div>
      </div>

      <!-- 消息列表区 -->
      <div class="messages-container" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <p>你好！我是你的情绪陪伴助手。</p>
          <p>分享你的心情，我在这里倾听。</p>
        </div>
        
        <div v-for="(message, index) in messages" :key="index" class="message-wrapper">
          <div :class="['message-bubble', message.sender === 'ai' ? 'ai-message' : 'user-message']">
            <img 
              :src="message.sender === 'ai' ? aiAvatar : userAvatar" 
              :alt="message.sender === 'ai' ? 'AI助手' : '你'" 
              class="avatar"
            >
            <div class="message-content">
              {{ message.content }}
            </div>
          </div>
        </div>
        
        <div v-if="isLoading" class="loading-message">
          <img :src="aiAvatar" alt="AI助手" class="avatar">
          <div class="message-content">
            <span class="loading-dots">正在倾听</span>
          </div>
        </div>
      </div>

      <!-- 输入区 -->
      <div class="input-container">
        <textarea 
          v-model="inputMessage" 
          @keyup.enter.ctrl="sendMessage" 
          placeholder="分享你的心情吧～"
          rows="1"
          maxlength="500"
          ref="textArea"
        ></textarea>
        <div class="input-footer">
          <span class="char-count">{{ inputMessage.length }}/500</span>
          <button 
            class="send-btn" 
            @click="sendMessage" 
            :disabled="!inputMessage.trim() || isLoading"
          >
            发送
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, nextTick, onMounted, onUnmounted } from 'vue';

export default {
  name: 'ChatView',
  setup() {
    const messages = ref([]);
    const inputMessage = ref('');
    const isLoading = ref(false);
    const showPrivacy = ref(false);
    const messagesContainer = ref(null);
    const textArea = ref(null);
    
    // 使用简单的SVG作为头像
    const aiAvatar = 'data:image/svg+xml;charset=utf-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22%3E%3Ccircle cx=%2250%22 cy=%2240%22 r=%2225%22 fill=%22%23bde0fe%22/%3E%3Cpath d=%22M35 65c0-10 15-20 35-20s35 10 35 20v15H35z%22 fill=%22%23a2d2ff%22/%3E%3Ccircle cx=%2240%22 cy=%2235%22 r=%225%22 fill=%22white%22/%3E%3Ccircle cx=%2260%22 cy=%2235%22 r=%225%22 fill=%22white%22/%3E%3Cpath d=%22M40 55c0-5 10-8 20-8s20 3 20 8%22 stroke=%22white%22 stroke-width=%223%22 fill=%22none%22/%3E%3C/svg%3E';
    const userAvatar = 'data:image/svg+xml;charset=utf-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22%3E%3Ccircle cx=%2250%22 cy=%2240%22 r=%2225%22 fill=%22%23ffd6ff%22/%3E%3Cpath d=%22M35 65c0-10 15-20 35-20s35 10 35 20v15H35z%22 fill=%22%23ffafcc%22/%3E%3C/svg%3E';

    // 自动滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    };

    // 模拟AI回复
    const generateAIResponse = (userInput) => {
      const responses = [
        '我理解你的感受，愿意听你更多分享。',
        '谢谢你的坦诚，你的情绪很重要。',
        '听起来你正在经历一些挑战，我在这里支持你。',
        '你的想法很有价值，继续说下去吧。',
        '我能感受到你的心情，这一定不容易。',
        '每个人都有情绪起伏，这是正常的。',
        '给自己一些时间和空间，慢慢来。',
        '你并不孤单，我在这里陪伴你。'
      ];
      
      // 根据关键词选择更相关的回复
      if (userInput.includes('难过') || userInput.includes('伤心') || userInput.includes('不开心')) {
        return '我很抱歉你感到难过。可以告诉我更多吗？有时候说出来会好受一些。';
      } else if (userInput.includes('开心') || userInput.includes('快乐') || userInput.includes('高兴')) {
        return '太棒了！看到你开心我也很开心。能分享一下是什么让你这么开心吗？';
      } else if (userInput.includes('压力') || userInput.includes('焦虑') || userInput.includes('紧张')) {
        return '压力和焦虑确实很辛苦。试着深呼吸，你已经做得很好了。';
      } else {
        return responses[Math.floor(Math.random() * responses.length)];
      }
    };

    // 发送消息
    const sendMessage = async () => {
      if (!inputMessage.value.trim() || isLoading.value) return;
      
      const userMsg = inputMessage.value.trim();
      messages.value.push({ sender: 'user', content: userMsg });
      inputMessage.value = '';
      
      // 重置输入框高度
      if (textArea.value) {
        textArea.value.style.height = 'auto';
      }
      
      scrollToBottom();
      isLoading.value = true;
      
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 生成AI回复
        const aiResponse = generateAIResponse(userMsg);
        messages.value.push({ sender: 'ai', content: aiResponse });
      } catch (error) {
        console.error('发送消息失败:', error);
        messages.value.push({ 
          sender: 'ai', 
          content: '抱歉，我暂时无法回应。请稍后再试。' 
        });
      } finally {
        isLoading.value = false;
        scrollToBottom();
      }
    };

    // 自动调整输入框高度
    const adjustTextareaHeight = () => {
      if (textArea.value) {
        textArea.value.style.height = 'auto';
        textArea.value.style.height = Math.min(textArea.value.scrollHeight, 120) + 'px';
      }
    };

    onMounted(() => {
      // 添加输入事件监听
      if (textArea.value) {
        textArea.value.addEventListener('input', adjustTextareaHeight);
      }
      
      // 模拟初次AI问候
      setTimeout(() => {
        messages.value.push({ 
          sender: 'ai', 
          content: '你好！我是你的情绪陪伴助手。无论你有什么心情，都可以和我分享。' 
        });
        scrollToBottom();
      }, 500);
    });

    onUnmounted(() => {
      if (textArea.value) {
        textArea.value.removeEventListener('input', adjustTextareaHeight);
      }
    });

    // 动态加载loading dots动画
    const loadingDots = ref('正在倾听');
    let loadingInterval;
    
    onMounted(() => {
      loadingInterval = setInterval(() => {
        if (isLoading.value) {
          if (loadingDots.value === '正在倾听') loadingDots.value = '正在倾听.';
          else if (loadingDots.value === '正在倾听.') loadingDots.value = '正在倾听..';
          else if (loadingDots.value === '正在倾听..') loadingDots.value = '正在倾听...';
          else loadingDots.value = '正在倾听';
        }
      }, 500);
    });

    onUnmounted(() => {
      if (loadingInterval) clearInterval(loadingInterval);
    });

    return {
      messages,
      inputMessage,
      isLoading,
      showPrivacy,
      messagesContainer,
      textArea,
      aiAvatar,
      userAvatar,
      loadingDots,
      sendMessage
    };
  }
};
</script>

<style scoped>
.chat-page-container {
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.page-title {
  color: #4c51bf;
  margin-bottom: 20px;
  font-size: 24px;
  text-align: center;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
  width: 100%;
  background-color: #f8f9ff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 顶部标题栏 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid #e9ecef;
  z-index: 100;
}

.chat-header h1 {
  font-size: 18px;
  font-weight: 600;
  color: #4a5568;
  margin: 0;
}

.privacy-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background-color: #e6f7ff;
  color: #1890ff;
  border: none;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.privacy-btn:hover {
  background-color: #bae7ff;
  transform: translateY(-1px);
}

/* 隐私说明弹窗 */
.privacy-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.privacy-content {
  background-color: white;
  padding: 24px;
  border-radius: 16px;
  max-width: 400px;
  width: 90%;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
}

.privacy-content h3 {
  color: #4a5568;
  margin-bottom: 12px;
}

.privacy-content p {
  color: #718096;
  margin-bottom: 20px;
  line-height: 1.6;
}

.close-btn {
  padding: 8px 24px;
  background-color: #4c51bf;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.close-btn:hover {
  background-color: #434190;
}

/* 消息列表区 */
.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.welcome-message {
  text-align: center;
  color: #718096;
  margin-top: 40px;
  line-height: 1.8;
}

/* 消息气泡 */
.message-wrapper {
  display: flex;
}

.message-bubble {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  max-width: 70%;
}

.ai-message {
  align-self: flex-start;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
  font-size: 15px;
}

.ai-message .message-content {
  background-color: #ffffff;
  color: #4a5568;
  border-bottom-left-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-message .message-content {
  background-color: #4c51bf;
  color: white;
  border-bottom-right-radius: 6px;
  box-shadow: 0 2px 8px rgba(76, 81, 191, 0.2);
}

/* 加载状态 */
.loading-message {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  align-self: flex-start;
  max-width: 70%;
}

.loading-dots::after {
  content: '';
  animation: dots 1.5s infinite;
}

@keyframes dots {
  0%, 20% {
    content: '';
  }
  40% {
    content: '.';
  }
  60% {
    content: '..';
  }
  80%, 100% {
    content: '...';
  }
}

/* 输入区 */
.input-container {
  background-color: #ffffff;
  padding: 16px 20px;
  border-top: 1px solid #e9ecef;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
}

.input-container textarea {
  width: 100%;
  min-height: 40px;
  max-height: 120px;
  padding: 10px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 20px;
  resize: none;
  outline: none;
  font-size: 15px;
  line-height: 1.5;
  font-family: inherit;
  transition: border-color 0.3s ease;
}

.input-container textarea:focus {
  border-color: #4c51bf;
}

.input-container textarea::placeholder {
  color: #a0aec0;
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.char-count {
  font-size: 12px;
  color: #a0aec0;
}

.send-btn {
  padding: 8px 20px;
  background-color: #4c51bf;
  color: white;
  border: none;
  border-radius: 16px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-btn:hover:not(:disabled) {
  background-color: #434190;
  transform: translateY(-1px);
}

.send-btn:disabled {
  background-color: #e2e8f0;
  color: #a0aec0;
  cursor: not-allowed;
  transform: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
    height: 500px;
  }
  
  .chat-header {
    padding: 12px 16px;
  }
  
  .chat-header h1 {
    font-size: 16px;
  }
  
  .messages-container {
    padding: 16px;
  }
  
  .message-bubble {
    max-width: 85%;
  }
  
  .input-container {
    padding: 12px 16px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 20px;
  }
  
  .chat-header {
    padding: 10px 12px;
  }
  
  .privacy-btn {
    font-size: 12px;
    padding: 4px 8px;
  }
  
  .message-bubble {
    max-width: 90%;
  }
  
  .message-content {
    font-size: 14px;
    padding: 10px 14px;
  }
}
</style>